var dataList = [],
	index = 'all',
	doms = {
		actionModal: null
	},
	currentMessageId = null;

$(() => {
	doms.actionModal = document.getElementById('actionModal');
	initTags();
	loadData();
	initListener();
})

initTags = () => {
	const tags = new Tag({
		data: getTagsData(),
		container: '#tags',
		onChange: res => {
			index = res.key;
			loadData();
		}
	})
}

initListener = () => {
	$("#loading_layout").on('click', (e) => {
		loadData();
	});
	$(".modal-close").on('click', (e) => {
		closeActionModal();
	});
	$(".mark-read").on('click', (e) => {
		toggleReadStatus(currentMessageId);
		closeActionModal();
	});
	$(".mark-unread").on('click', (e) => {
		toggleReadStatus(currentMessageId);
		closeActionModal();
	});
	$(".delete").on('click', (e) => {
		deleteMessage(currentMessageId);
		closeActionModal();
	});
}

// 切换已读/未读状态
function toggleReadStatus(messageId) {
	const messageIndex = dataList.findIndex(msg => msg.id === messageId);
	if (messageIndex !== -1) {
		dataList[messageIndex].read = !dataList[messageIndex].read;
		loadData();
	}
}

// 删除消息
function deleteMessage(messageId) {
	dataList = dataList.filter(msg => msg.id !== messageId);
	loadData();
}

loadData = () => {
	setLoadingState(0);
	$("#list").html('');
	setTimeout(() => {
		let res = getMessageList();
		setLoadingState(1);
		if (res.code == 200) {
			let messages = res.data;
			let filteredMessages = messages;
			if (index === 'unread') {
				filteredMessages = messages.filter(msg => !msg.read);
			} else if (index === 'read') {
				filteredMessages = messages.filter(msg => msg.read);
			}
			renderList(filteredMessages);
		} else {
			setLoadingState(2);
		}
	}, 500)
}

getItem = (id) => {
	currentMessageId = id;
	showActionModal(id);
}

// 显示操作模态框
function showActionModal(messageId) {
	//currentMessageId = messageId;
	//const message = messages.find(msg => msg.id === messageId);
	//$("#actionModal").html('');
	doms.actionModal.classList.add('active');
	document.body.style.overflow = 'hidden';
}

// 关闭操作模态框
function closeActionModal() {
	doms.actionModal.classList.remove('active');
	document.body.style.overflow = '';
}

renderList = mList => {
	$("#list").html('');
	if (ArrayEmpty(mList)) return setLoadingState(2, noData());

	mList.forEach(message => {
		const messageItem = document.createElement('div');
		messageItem.className = `message-item ${message.read ? '' : 'unread'}`;
		messageItem.dataset.id = message.id;
		messageItem.addEventListener('click', () => {
			getItem(message.id);
		})

		messageItem.innerHTML = `
	        <div class="message-icon">
	            <i class="${getMessageIcon(message.type)}"></i>
	        </div>
	        <div class="message-content">
	            <div class="message-title">
	                <span>${message.title}</span>
	                <span class="message-time">${formatTime(message.time)}</span>
	            </div>
	            <p class="message-text">${message.content}</p>
	            <div class="message-actions">
	                <button class="action-btn mark-btn">
	                    <i class="fas fa-${message.read ? 'envelope' : 'envelope-open'}"></i>
	                    ${message.read ? '标记未读' : '标记已读'}
	                </button>
	                <button class="action-btn delete-btn">
	                    <i class="fas fa-trash-alt"></i>
	                    删除
	                </button>
	            </div>
	        </div>
	    `;
		$("#list").append(messageItem);
	});
}

// 获取消息图标
function getMessageIcon(type) {
	const icons = {
		'order': 'fa-shopping-bag',
		'promotion': 'fa-percentage',
		'system': 'fa-cog',
		'activity': 'fa-gift'
	};
	return icons[type] || 'fa-bell';
}

// 获取消息标题
function getMessageTitle(type, index) {
	const titles = {
		'order': ['订单发货通知', '订单支付成功', '订单已完成'],
		'promotion': ['限时特惠', '会员专享折扣', '新品上市'],
		'system': ['系统维护通知', '账户安全提醒', '新版本更新'],
		'activity': ['周年庆活动', '邀请有礼', '节日特惠']
	};
	const typeTitles = titles[type];
	return typeTitles[Math.floor(Math.random() * typeTitles.length)];
}

// 获取消息内容
function getMessageContent(type) {
	const contents = {
		'order': '您的订单已发货，预计3-5个工作日送达。点击查看物流详情。',
		'promotion': '会员专享8折优惠，活动仅限今日，快来选购吧！',
		'system': '系统将于今晚23:00-24:00进行维护升级，期间可能无法正常访问。',
		'activity': '参与邀请好友活动，最高可获得100元优惠券，立即参与！'
	};
	return contents[type] || '您有一条新消息，请点击查看详情。';
}

// 格式化时间
function formatTime(date) {
	const now = new Date();
	const diff = now - new Date(date);

	if (diff < 60 * 1000) {
		return '刚刚';
	} else if (diff < 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 1000))}分钟前`;
	} else if (diff < 24 * 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
	} else {
		return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
	}
}
